var SecurityUtil = require('../lib/utils/SecurityUtil');
var connection = require('../lib/utils/DbconnectUtil');
var _ = require("underscore");

var config = require("../config/setting");

var express = require('express');
var router = express.Router();

router.post('/login/', function (req, res, next) {

    var username = req.body.username;
    var password = req.body.password;
    var resData = {};

    if (!username || !password) {
        resData.result = false;
        resData.message = "用户名或密码不存在";
        res.send(resData);
        return ;
    }

    //校验管理员账户
    var accountValidFlag = checkAdminAccounts(username);
    if(!accountValidFlag){
        resData.result = false;
        resData.message = "非管理员账户无法登录";
        res.send(resData);
        return ;
    }

    var queryStr = 'select * from t_user where user_name = ? ';
    connection().query(queryStr, [username], function (err, results) {
        if (err) {
            res.send({
                result: false,
                message: '服务器内部异常'
            });
        } else if (results && results[0]) {
            var chipher = SecurityUtil.genPasswordCipherText(password, results[0].salt);
            if (chipher === results[0].password) {
                var jwtToken = SecurityUtil.getJwtSign(results[0]);
                res.cookie('jwtToken', jwtToken, {maxAge: 7200000,  path: '/'});
                res.cookie('adminAuth', true, {maxAge: 7200000,  path: '/'});

                res.send({
                    result: true,
                    user: {
                        id: results[0].id,
                        nickName: results[0].nick_name,
                        userName: results[0].user_name,
                        phoneNumber: results[0].phone_number,
                        email: results[0].email
                    }
                });
            } else {
                res.send({
                    result: false,
                    message: '用户或密码不正确'
                });
            }
        }
        else {
            res.send({
                result: false,
                message: '当前用户不存在'
            });
        }
    });

});

function checkAdminAccounts(username) {
    var validFlag = false;
    _.forEach(config.adminAccounts, function (item) {
        if (item == username) {
            validFlag  = true;
            return ;
        }
    })
    return validFlag;
}

router.get('/loginState/', function (req, res, next) {

    console.log('#### jwtToken #### '+ req.cookies.jwtToken);

    if(req.cookies.jwtToken && req.cookies.adminAuth){
        res.send({result:true,message:"有效的登录状态"});
    }else {
        res.send({result:false,message:"当前用户未登录"});
    }

});

router.post('/logout/', function (req, res, next) {
    console.log('logout....');
    res.clearCookie('jwtToken', { path: '/' });
    res.clearCookie('adminAuth', { path: '/' });
    res.send({
        result: true,
        message: '已经退出登录'
    });
});


module.exports = router;
